﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interactivity;


namespace D3StatsClient.Behaviours
{
    public class ListViewAutoScrollBehaviour : Behavior<DataGrid>
    {
        public static readonly DependencyProperty AutoScrollProperty =
        DependencyProperty.Register("AutoScroll", typeof(bool), typeof(ListViewAutoScrollBehaviour), null);

        public bool AutoScroll
        {
            get { return (bool)GetValue(AutoScrollProperty); }
            set { SetValue(AutoScrollProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            var collection = AssociatedObject.Items.SourceCollection as INotifyCollectionChanged;

            if (collection != null)
            {
                collection.CollectionChanged += collection_CollectionChanged;
            }
        }

        void collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (AssociatedObject.Items.Count > 0 && e.Action == NotifyCollectionChangedAction.Add)
            {
                AssociatedObject.ScrollIntoView(AssociatedObject.Items[AssociatedObject.Items.Count - 1]);
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            var collection = AssociatedObject.Items.SourceCollection as INotifyCollectionChanged;

            if (collection != null)
            {
                collection.CollectionChanged -= collection_CollectionChanged;
            }
            
        }
    }
}
